package com.mofeng.myshop.service.impl;

import com.mofeng.myshop.domain.dto.ProjectDto;
import com.mofeng.myshop.domain.vo.ProjectVo;
import com.mofeng.myshop.service.IProjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mofeng.myshop.domain.po.Project;
import com.mofeng.myshop.mapper.IProjectMapper;
import com.mofeng.myshop.until.Constants;
import com.mofeng.myshop.until.MyUtil;
import com.mofeng.myshop.until.R;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 项目 服务实现类
 * </p>
 *
 * @author MoFeng
 * @since 2024-04-15
 */
@Service
@RequiredArgsConstructor
public class ProjectServiceImpl extends ServiceImpl<IProjectMapper, Project> implements IProjectService {

    private final IProjectMapper projectMapper;

    /**
     * 添加或者修改项目
     *
     * @param projectDto 项目信息
     * @return R
     */
    @Override
    @Transactional
    public R saveProject(ProjectDto projectDto) {
        Project project = projectDto.toProject();
        if (MyUtil.StringUtil.isEmpty(projectDto.getId())) {
            return createProject(project);
        } else {
            return updateProject(project);
        }
    }

    @Transactional
    protected R createProject(Project project) {
        String name = project.getName();
        if (MyUtil.StringUtil.isEmpty(name)) {
            return R.FAILED("项目名不能为空");
        }
        project.setOpen(Constants.State.DEFAULT_STATE);
        project.setShow(Constants.State.DEFAULT_STATE);
        projectMapper.insert(project);
        return R.SUCCESS("项目创建成功").setData(new ProjectVo(project));
    }

    @Transactional
    protected R updateProject(Project project) {
        projectMapper.updateById(project);
        return R.SUCCESS("项目修改完成");
    }

    /**
     * 批量删除
     */
    @Override
    public R deleteProject(List<String> ids) {
        List<Long> collect = ids.stream().map(Long::parseLong).toList();
        projectMapper.deleteBatchIds(collect);
        return R.SUCCESS("项目删除完成");
    }

    /**
     * 后台获取全部项目列表
     */
    @Override
    public R getListAdmin() {
        List<Project> projects = projectMapper.findByShow(null);
        return R.SUCCESS().setData(ProjectVo.change(projects));
    }

    /**
     * 前台获取全部项目列表
     */
    @Override
    public R getListPortal() {
        List<Project> projects = projectMapper.findByShow(Constants.State.DEFAULT_STATE);
        return R.SUCCESS().setData(ProjectVo.change(projects));
    }
}
